<title>服务提供者</title>
<div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
        <a><cite>项目管理</cite></a>
        <a><cite>服务提供者</cite></a>
    </div>
</div>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-form layui-card-header layuiadmin-card-header-auto" lay-filter="content-producer">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <input type="text" name="name" placeholder="服务名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn layuiadmin-btn-producer" lay-submit lay-filter="LAY-producer-search">
                        搜索
                    </button>
                    <button class="layui-btn producer-btn-common" data-type="add">
                        添加
                    </button>
                </div>
            </div>
        </div>
        <div class="layui-card-body">
            <table id="LAY-producer" lay-filter="LAY-producer"></table>
            <script type="text/html" id="table-system-producer">
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i
                        class="layui-icon layui-icon-edit"></i>编辑</a>
                <!--                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i-->
                <!--                        class="layui-icon layui-icon-delete"></i>删除</a>-->
                <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">
                    <i class="layui-icon layui-icon-about"></i>详情
                </a>
            </script>
        </div>
    </div>
</div>

<script>
    layui.use(['admin', 'table', 'form', 'setter', 'element'], function () {
        var $ = layui.$
            , admin = layui.admin
            , view = layui.view
            , table = layui.table
            , form = layui.form
            , element = layui.element
            , setter = layui.setter;

        var apiUrl = setter.apiUrl;

        table.render({
            elem: '#LAY-producer'
            , url: apiUrl + '/mapi/producer/list'
            , method: 'post'
            , page: true
            , contentType: 'application/json'
            , headers: {'token': layui.data(setter.tableName).token}
            , request: {
                pageName: 'pageNo'
                , limitName: 'pageSize'
            }
            , response: {
                statusCode: 0, //规定数据状态的字段名称，默认：code
            }
            , parseData: function (res) {
                if (res.code === 0) {
                    //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                } else {
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                    };
                }
            }
            , cols: [[
                {field: 'name', width: 180, title: '服务名称'}
                , {field: 'loadIp', width: 170, title: '请求地址'}
                , {field: 'protocol', width: 100, title: '服务类型'}
                , {field: 'translateProtocol', width: 100, title: '格式'}
                , {field: 'enable', width: 60, title: '状态', templet: '<div>{{d.enable==0?"禁用":"正常"}}</div>'}
                , {
                    field: 'createdAt',
                    title: '创建时间',
                    minWidth: 170,
                    templet: '<div>{{layui.util.toDateString(d.createdAt, "yyyy-MM-dd HH:mm:ss")}}</div>'
                }
                , {title: '操作', minWidth: 250, fixed: 'right', toolbar: '#table-system-producer'}
            ]]
            , text: {
                none: '未检索到数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
            }
            , done: function () {
                element.render('progress');
            }
        });

        //监听工具条
        table.on('tool(LAY-producer)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                admin.popup({
                    title: '编辑服务项目'
                    , area: ['70%', '100%']
                    , id: 'LAY-popup-producer-edit'
                    , success: function (layero, index) {
                        view(this.id).render('project/producer/edit', data).done(function () {
                            var pid = data.id;
                            form.render(null, 'form-producer');
                            //监听提交
                            form.on('submit(LAY-producer-edit-submit)', function (data) {
                                var formData = data.field;
                                var loadBalance = {};
                                if (!isEmpty(formData.loadBalanceIdArray)) {
                                    //{"strategy":"ROUND","retryTime":"1","data":[{"server":"127.0.0.1","weight":"1"}]}
                                    var balanceIdArray = formData.loadBalanceIdArray.split(',')
                                    var balanceData = [];
                                    for (var i = 0; i < balanceIdArray.length; i++) {
                                        let idx = balanceIdArray[i];
                                        let idxServer = 'server[' + idx + ']';
                                        let idxWeight = 'weight[' + idx + ']';
                                        var server = formData[idxServer];
                                        delete formData[idxServer];
                                        var weight = formData[idxWeight];
                                        delete formData[idxWeight];
                                        var single = {"server": server, "weight": weight};
                                        balanceData.push(single);
                                    }
                                    loadBalance['strategy'] = formData.strategy;
                                    loadBalance['retryTime'] = formData.retryTime;
                                    loadBalance['data'] = balanceData;
                                }
                                formData['loadBalance'] = loadBalance;


                                // formData['hystrixParam'] = {
                                //     "commandKey": formData['commandKey'],
                                //     "errorThresholdPercentage": formData['errorThresholdPercentage'],
                                //     "groupKey": formData['groupKey'],
                                //     "requestVolumeThreshold": formData['requestVolumeThreshold'],
                                //     "sleepWindowInMilliseconds": formData['sleepWindowInMilliseconds'],
                                //     "timeoutInMilliseconds": formData['timeoutInMilliseconds']
                                // };

                                var grayRelease = {};
                                if (!isEmpty(formData.grayIpIdArray)) {
                                    var grayIpIdArray = formData.grayIpIdArray.split(',')
                                    console.log(grayIpIdArray);
                                    var ipList = [];
                                    for (var j = 0; j < grayIpIdArray.length; j++) {
                                        let idx = grayIpIdArray[j];
                                        let idxIp = 'ip[' + idx + ']';
                                        var ip = formData[idxIp];
                                        delete formData[idxIp];
                                        if (!isEmpty(ip)) {
                                            ipList.push(ip);
                                        }
                                    }
                                    grayRelease['ips'] = ipList;
                                    grayRelease['server'] = formData.server;
                                }
                                formData['grayRelease'] = grayRelease;
                                console.log(formData);

                                delete formData['server'];
                                delete formData['strategy'];
                                delete formData['retryTime'];
                                // delete formData['commandKey'];
                                // delete formData['errorThresholdPercentage'];
                                // delete formData['groupKey'];
                                // delete formData['requestVolumeThreshold'];
                                // delete formData['sleepWindowInMilliseconds'];
                                // delete formData['timeoutInMilliseconds'];
                                delete formData['loadBalanceIdArray'];
                                delete formData['grayIpIdArray'];

                                console.log(formData);
                                admin.req({
                                    url: apiUrl + '/mapi/producer/update/' + pid
                                    , method: 'put'
                                    , data: JSON.stringify(data.field)
                                    , done: function (response) {
                                        if (response.code === 0) {
                                            layer.msg('修改成功', {
                                                offset: '15px', icon: 1, time: 1000
                                            }, function () {
                                                layui.table.reload('LAY-producer');
                                                layer.close(index);
                                            });
                                        } else {
                                            layer.msg(response.msg, {
                                                offset: '15px', icon: 2
                                            });
                                        }
                                    }
                                });
                            });
                        });
                    }
                });
            } else if (obj.event === 'detail') {
                admin.popup({
                    title: '服务项目详情'
                    , area: ['70%', '100%']
                    , id: 'LAY-popup-producer-detail'
                    , success: function (layero, index) {
                        view(this.id).render('project/producer/detail', data).done(function () {
                            form.render(null, 'form-producer');
                        });
                    }
                });
            }
        });

        //事件
        var active = {
            add: function () {
                admin.popup({
                    title: '添加服务项目'
                    , area: ['70%', '100%']
                    , id: 'LAY-popup-producer-add'
                    , success: function (layero, index) {
                        view(this.id).render('project/producer/add').done(function () {
                            //监听提交
                            form.on('submit(LAY-producer-add-submit)', function (data) {
                                var formData = data.field;
                                console.log(data.field);
                                var loadBalance = {};
                                if (!isEmpty(formData.loadBalanceIdArray)) {
                                    //{"strategy":"ROUND","retryTime":"1","data":[{"server":"127.0.0.1","weight":"1"}]}
                                    var balanceIdArray = formData.loadBalanceIdArray.split(',')
                                    var balanceData = [];
                                    for (var i = 0; i < balanceIdArray.length; i++) {
                                        let idx = balanceIdArray[i];
                                        let idxServer = 'server[' + idx + ']';
                                        let idxWeight = 'weight[' + idx + ']';
                                        var server = formData[idxServer];
                                        delete formData[idxServer];
                                        var weight = formData[idxWeight];
                                        delete formData[idxWeight];
                                        var single = {"server": server, "weight": weight};
                                        balanceData.push(single);
                                    }
                                    loadBalance['strategy'] = formData.strategy;
                                    loadBalance['retryTime'] = formData.retryTime;
                                    loadBalance['data'] = balanceData;
                                }
                                formData['loadBalance'] = loadBalance;


                                // formData['hystrixParam'] = {
                                //     "commandKey": formData['commandKey'],
                                //     "errorThresholdPercentage": formData['errorThresholdPercentage'],
                                //     "groupKey": formData['groupKey'],
                                //     "requestVolumeThreshold": formData['requestVolumeThreshold'],
                                //     "sleepWindowInMilliseconds": formData['sleepWindowInMilliseconds'],
                                //     "timeoutInMilliseconds": formData['timeoutInMilliseconds']
                                // };

                                var grayRelease = {};
                                if (!isEmpty(formData.grayIpIdArray)) {
                                    var grayIpIdArray = formData.grayIpIdArray.split(',')
                                    console.log(grayIpIdArray);
                                    var ipList = [];
                                    for (var j = 0; j < grayIpIdArray.length; j++) {
                                        let idx = grayIpIdArray[j];
                                        let idxIp = 'ip[' + idx + ']';
                                        var ip = formData[idxIp];
                                        delete formData[idxIp];
                                        if (!isEmpty(ip)) {
                                            ipList.push(ip);
                                        }
                                    }
                                    grayRelease['ips'] = ipList;
                                    grayRelease['server'] = formData.server;
                                }
                                formData['grayRelease'] = grayRelease;
                                console.log(formData);

                                delete formData['server'];
                                delete formData['strategy'];
                                delete formData['retryTime'];
                                // delete formData['commandKey'];
                                // delete formData['errorThresholdPercentage'];
                                // delete formData['groupKey'];
                                // delete formData['requestVolumeThreshold'];
                                // delete formData['sleepWindowInMilliseconds'];
                                // delete formData['timeoutInMilliseconds'];
                                delete formData['loadBalanceIdArray'];
                                delete formData['grayIpIdArray'];

                                console.log(formData);

                                admin.req({
                                    url: apiUrl + '/mapi/producer/add'
                                    , method: 'post'
                                    , data: JSON.stringify(formData)
                                    , done: function (response) {
                                        if (response.code === 0) {
                                            layer.msg('添加成功', {
                                                offset: '15px', icon: 1, time: 1000
                                            }, function () {
                                                layui.table.reload('LAY-producer');
                                                layer.close(index);
                                            });
                                        } else {
                                            layer.msg(response.msg, {
                                                offset: '15px', icon: 2
                                            });
                                        }
                                    }
                                });
                            });
                        });
                    }
                });
            }
        };


        form.render(null, 'content-producer');

        //监听搜索
        form.on('submit(LAY-producer-search)', function (data) {
            var field = data.field;
            //执行重载
            table.reload('LAY-producer', {
                where: field
            });
        });

        $('.layui-btn.producer-btn-common').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        function isEmpty(str) {
            if (typeof str == null || str == "" || str == "undefined") {
                return true;
            } else {
                return false;
            }
        }
    });
</script>